﻿package molecule.render.starling.states.controllers 
{
    import molecule.logger;
    import molecule.render.starling.states.process.OpenState;
    import molecule.states.State;

    import system.ioc.factory;
    import system.process.Chain;
    import system.signals.Receiver;
    
    /**
     * Invoked when the state model is changed.
     */
    public class ChangeState implements Receiver 
    {
        /**
         * Creates a new ChangeState instance.
         * @param chain the Chain object used to do the transition between the beforeChange and change states. 
         * @param auto Indicates if the screen of the current state is automatically attached when the state is opened (default true).
         * @param factory The optional ioc factory reference (by default use the system.ioc.factory).
         */
        public function ChangeState( chain:Chain = null , auto:Boolean = true , factory:ObjectFactory = null )
        {
            this.chain   = chain ;
            this.auto    = auto ;
            this.factory = factory ;
        }
        
        /**
         * Indicates if the screen of the current state is automatically attached when the state is opened (default true).
         */
        public var auto:Boolean = true ;

        /**
         * The state Chain reference of the state engine.
         */
        public var chain:Chain ;

        /**
         * The ioc factory reference.
         */
        public var factory:ObjectFactory ;

        /**
         * Receive the message.
         */
        public function receive( ...args:Array ):void 
        {
            var state:State = args[0] as State ;

            logger.info( this + " handleEvent : " + state ) ;
            
            if ( chain && state )
            {
                chain.addAction( new OpenState( state , this.factory || system.ioc.factory , auto ) , 0 , true ) ;
                if ( !chain.running )
                {
                    chain.run() ;
                }
            }
            else
            {
                logger.warn(this + " failed with the vo:" + state + " and the chain:" + chain ) ; 
            }
        }
    }
}
